package cn.edu.scnu.controller;

import cn.edu.scnu.entity.User;
import cn.edu.scnu.service.UserService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {

    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.merchantPrivateKey}")
    private String merchantPrivateKey;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @Autowired
    private UserService userService;

    //支付接口，生成支付宝支付页面链接
    @GetMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam Integer price, @RequestParam String subject) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey, "json", "utf-8", alipayPublicKey, "RSA2");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime now = LocalDateTime.now();
        String timestamp = now.format(dtf);

        request.setBizContent("{" +
                "\"out_trade_no\":\""+timestamp+"\"," + // 商户订单号为当前时间戳
                "\"total_amount\":"+price.toString()+"," + // 支付金额
                "\"subject\":\""+subject+"\"," + // 订单标题
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}" // 产品码
        );

        String form = alipayClient.pageExecute(request).getBody();
        return form; // 返回表单
    }

    @PostMapping("/notify")
    @ResponseBody
    public String handleNotify(HttpServletRequest request, HttpSession session) throws AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
        if (signVerified) {
            // 验证成功，处理通知
            System.out.println("Async notification received and verified.");

            // 获取当前用户，更改为vip
            User loggedUser = (User) session.getAttribute("user");
            if (loggedUser != null) {
                loggedUser.setIsVip(1);
                userService.updateUser(loggedUser);
                session.setAttribute("user", loggedUser);
            }

            // 更新订单状态等业务逻辑
            return "success";
        } else {
            // 验证失败
            System.out.println("Async notification verification failed.");
            return "failure";
        }
    }

    @GetMapping("/return")
    public String handleReturn(HttpServletRequest request) {

        return "index";// 返回支付完成后的页面
    }
}

